<template>
  <div>
    <div>
      <!--按钮列表-->
      <el-button-group class="toolBox">
        <el-button size="small" v-for="(item,index) in buttonGroups" :key="index" @click="dynamicMethod(item.method,item.params)" :icon="item.icon">
          {{item.label}}</el-button>
      </el-button-group>
    </div>
    <!--数据表格-->
    <el-row>
      <el-col :span="24">
        <el-table :data="tableData" border stripe highlight-current-row ref="multipleTable" :height="tableHeight" @row-click="handleRowClick"
          style="width: 100%">
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column type="index" width="65" label="序号" align="center" fixed :show-overflow-tooltip="true"></el-table-column>
          <template v-for="(el,i) in tableColumns">
            <el-table-column :label="el.label" header-align="center" v-if="el.show && el.prop === 'publicationDate'" :width="el.width || ''"
              :key="el.prop" :fixed="el.fixed" :prop="el.prop" :sortable="el.sortable" show-overflow-tooltip>
              <template slot-scope="scope">{{
                scope.row.publicationDate | dateFormat
              }}</template>
            </el-table-column>
            <el-table-column :label="el.label" header-align="center" v-else-if="el.show " :width="el.width || ''" :key="el.prop" :fixed="el.fixed"
              :prop="el.prop" :sortable="el.sortable" show-overflow-tooltip>
            </el-table-column>
          </template>
          <el-table-column fixed="right" label="操作" width="150">
            <template slot-scope="scope">
              <el-button type="text" @click="handleInventoryClick(scope.row)" size="small">馆藏信息</el-button>
              <el-button type="text" @click="handleDelClick(scope.row)" size="small">删除</el-button>
              <el-button type="text" @click="handleEditClick(scope.row)" size="small">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <!--分页插件-->
    <el-row>
      <el-col :span="24">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="current" :page-sizes="pageSizeOptions"
          :page-size="size" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </el-col>
    </el-row>
    <!--列自定义-->
    <CustomTableCols :defaultCols="defaultColumns" customName="book" @changeColumns="changeColumns" />
    <!--查询条件-->
    <Search :show.sync="showSearch" :condition="searchCondition" :form="searchForm" @ok="setCondition" @hidden="hidCondition" />
    <!--新增编辑页面-->
    <CustomForm :show.sync="showForm" title="图书编辑" :control="formControl" :model="formField" :rules="formRules" @ok="saveForm" @hidden="hidForm" />

    <!--字典子列表页面-->
    <el-drawer title="图书馆藏" :visible.sync="showDrawer" custom-class="demo-drawer" ref="drawer" size="90%">
      <div class="demo-drawer__content">
        <!-- <BookInventory /> -->
        <div>
          <!--按钮列表-->
          <el-button-group class="toolBox">
            <el-button size="small" v-for="(item,index) in buttonGroupsInv" :key="index" @click="dynamicMethod(item.method,item.params)"
              :icon="item.icon">
              {{item.label}}</el-button>
          </el-button-group>
        </div>
        <!--数据表格-->
        <el-row>
          <el-col :span="24">
            <el-table :data="tableDataInv" border stripe highlight-current-row ref="multipleTableInv" :height="tableHeightInv"
              @row-click="handleRowClickInv" style="width: 100%">
              <template v-for="(el,i) in tableColumnsInv" :v-bind="i">
                <el-table-column :label="el.label" header-align="center" v-if="el.show " :width="el.width || ''" :key="el.prop" :fixed="el.fixed"
                  :prop="el.prop" :sortable="el.sortable" show-overflow-tooltip>
                </el-table-column>
              </template>
              <el-table-column fixed="right" label="操作" width="150">
                <template slot-scope="scope">
                  <el-button type="text" @click="handleEditInvClick(scope.row)" size="small">编辑</el-button>
                  <el-button type="text" @click="handleDelInvClick(scope.row)" size="small">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <!--分页插件-->
        <el-row>
          <el-col :span="24">
            <el-pagination @size-change="handleSizeChangeInv" @current-change="handleCurrentChangeInv" :current-page="currentInv"
              :page-sizes="pageSizeOptions" :page-size="sizeInv" layout="total, sizes, prev, pager, next, jumper" :total="totalInv">
            </el-pagination>
          </el-col>
        </el-row>
        <!--列自定义-->
        <CustomTableCols :defaultCols="defaultColumnsInv" customName="bookInventory_book" @changeColumns="changeColumnsInv" />
        <!--查询条件-->
        <Search :show.sync="showSearchInv" :condition="searchConditionInv" :form="searchFormInv" @ok="setConditionInv" @hidden="hidConditionInv" />
        <!--新增编辑页面-->
        <CustomForm :show.sync="showFormInv" title="馆藏编辑" :control="formControlInv" :model="formFieldInv" :rules="formRules" @ok="saveFormInv"
          @hidden="hidFormInv" />
      </div>
    </el-drawer>

  </div>

</template>

<script>
import CustomTableCols from '../../components/CustomTableCols'
import Search from '../../components/Search'
import CustomForm from '../../components/CustomForm'
import BookInventory from '../../components/BookInventory'
export default {
  components: {
    CustomTableCols,
    Search,
    CustomForm,
    BookInventory
  },
  data() {
    return {
      initData: {},
      tableData: [],
      tableHeight: '400px',
      current: 1,
      size: 10,
      total: 0,
      pageSizeOptions: [10, 20, 50, 100],
      searchForm: { bookName: '', bookBarCode: '', author: '', publisher: '', interpreter: '', printing: '', catalogId: '', canBorrow: '' },
      searchCondition: [
        { index: 0, label: '图书名称', field: 'bookName', type: 'input', show: true },
        { index: 1, label: '图书条码', field: 'bookBarCode', type: 'input', show: true },
        { index: 2, label: '作者', field: 'author', type: 'input', show: true },
        { index: 3, label: '出版社', field: 'publisher', type: 'input', show: true },
        { index: 4, label: '翻译者', field: 'interpreter', type: 'input', show: true },
        { index: 5, label: '印刷单位', field: 'printing', type: 'input', show: true },
        { index: 6, label: '图书分类', field: 'catalogId', type: 'select', show: true, options: this.catalogArray },
        { index: 7, label: '可借阅', field: 'canBorrow', type: 'select', options: [{ label: '是', value: '1' }, { label: '否', value: '0' }], show: true },
      ],
      showSearch: false,
      buttonGroups: [
        { index: 0, label: '查询', method: 'showCondition', icon: 'el-icon-search' },
        { index: 1, label: '新建', method: 'addAndEdit', icon: 'el-icon-plus' },
        { index: 2, label: '禁止借阅', method: 'enableUser', params: false, icon: 'el-icon-delete' },
        { index: 5, label: '删除', method: 'delete', icon: 'el-icon-delete' },
        { index: 6, label: '刷新', method: 'searchData', icon: 'el-icon-refresh' }
      ],
      tableColumns: [],
      defaultColumns: [
        { label: '图书名称', prop: 'bookName', show: true, fixed: false, sortable: false, width: 150 },
        { label: '图书条码', prop: 'bookBarCode', show: true, fixed: false, sortable: false, width: 120 },
        { label: '作者', prop: 'author', show: true, fixed: false, sortable: false },
        { label: '出版社', prop: 'publisher', show: true, fixed: false, sortable: false },
        { label: '出版日期', prop: 'publicationDate', show: true, fixed: false, sortable: false },
        { label: '印刷单位', prop: 'printing', show: true, fixed: false, sortable: false },
        { label: '翻译者', prop: 'interpreter', show: true, fixed: false, sortable: false },
        { label: '价格', prop: 'price', show: true, fixed: false, sortable: false },
        { label: '图书分类', prop: 'catalogName', show: true, fixed: false, sortable: false },
        { label: '是否可以借阅', prop: 'canBorrow', show: true, fixed: false, sortable: false },
        { label: '借阅天数', prop: 'borrowDay', show: true, fixed: false, sortable: false }
      ],
      showForm: false,
      formField: { id: '', bookName: '', bookBarCode: '', author: '', publisher: '', publicationDate: '', printing: '', interpreter: '', price: '', catalogId: '', catalogCode: '', catalogName: '', canBorrow: '', borrowDay: 60 },
      formControl: [
        { label: 'ID', field: 'id', type: 'hidden', show: false, readonly: true },
        { label: '图书条码', field: 'bookBarCode', type: 'input', show: true, readonly: true, placeholder: '系统自动生成' },
        { label: '图书名称', field: 'bookName', type: 'input', show: true, readonly: false },
        { label: '作者', field: 'author', type: 'input', show: true, readonly: false },
        { label: '出版社', field: 'publisher', type: 'input', show: true, readonly: false },
        { label: '出版日期', field: 'publicationDate', type: 'date', show: true, readonly: false },
        { label: '印刷单位', field: 'printing', type: 'input', show: true },
        { label: '翻译者', field: 'interpreter', type: 'input', show: true },
        { label: '价格', field: 'price', type: 'number', show: true, min: 1, max: 9999 },
        { label: '图书分类', field: 'catalogId', type: 'select', show: true, options: null },
        { label: '可借阅', field: 'canBorrow', type: 'select', show: true, options: [{ label: '是', value: '1' }, { label: '否', value: '0' },] },
        { label: '借阅天数', field: 'borrowDay', type: 'number', show: true, },
      ],
      formRules: {
        bookName: [
          { required: true, message: '请输入图书名称', trigger: 'blur' },
          { min: 1, max: 80, message: '长度在 1 到 80 个字符', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '请输入作者', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
        ],
        publisher: [
          { required: true, message: '请输入出版社', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        publicationDate: [
          { required: true, message: '请选择出版日期', trigger: 'blur' },
        ],
        printing: [
          { required: true, message: '请输入印刷单位', trigger: 'blur' }
        ],
        catalogId: [
          { required: true, message: '请选择所属图书分类', trigger: 'blur' }
        ]
      },
      multipleSelection: [],
      visible: false,
      checkedKeys: [],
      showTree: false,
      catalogArray: [],
      showDrawer: false,
      // searchFormInv: { bookName: '', bookBarCode: '', author: '', libraryId: '' },
      searchFormInv: { libraryId: '' },
      searchConditionInv: [
        // { index: 0, label: '图书名称', field: 'bookName', type: 'input', show: true },
        // { index: 1, label: '图书条码', field: 'bookBarCode', type: 'input', show: true },
        // { index: 2, label: '作者', field: 'author', type: 'input', show: true },
        { index: 5, label: '所在分馆', field: 'libraryId', type: 'input', show: true, type: 'select', show: true, options: this.libraryArray },
      ],
      showSearchInv: false,
      buttonGroupsInv: [
        { index: 0, label: '查询', method: 'showConditionInv', icon: 'el-icon-search' },
        { index: 1, label: '新建', method: 'addAndEditInv', icon: 'el-icon-plus' },
        { index: 6, label: '刷新', method: 'searchDataInv', icon: 'el-icon-refresh' }
      ],
      tableColumnsInv: [],
      defaultColumnsInv: [
        { label: '图书名称', prop: 'bookName', show: true, fixed: false, sortable: false, width: 150 },
        { label: '总本数', prop: 'totalQty', show: true, fixed: false, sortable: false },
        { label: '在馆数量', prop: 'inPavilion', show: true, fixed: false, sortable: false },
        { label: '借阅数量', prop: 'borrowQty', show: true, fixed: false, sortable: false },
        { label: '所在分馆', prop: 'libraryName', show: true, fixed: false, sortable: false },
      ],
      formFieldInv: { id: '', bookName: '', bookId: '', totalQty: '', inPavilion: '', borrowQty: '', libraryId: '' },
      formControlInv: [
        { label: 'ID', field: 'id', type: 'hidden', show: false, readonly: true },
        { label: '图书名称', field: 'bookName', type: 'input', show: true, readonly: false },
        { label: '总本数', field: 'totalQty', type: 'number', show: true, readonly: false },
        { label: '在馆数量', field: 'inPavilion', type: 'number', show: true, readonly: false },
        { label: '借阅数量', field: 'borrowQty', type: 'number', show: true, readonly: false },
        { label: '所在分馆', field: 'libraryId', type: 'select', show: true, options: null },
      ],
      formRulesInv: {
        bookName: [
          { required: true, message: '请输入图书名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        libraryId: [
          { required: true, message: '请选择图书分馆', trigger: 'blur' }
        ]
      },
      bookId: '',
      bookInfo: null,
      showFormInv: false,
      tableDataInv: [],
      tableHeightInv: '400px',
      currentInv: 1,
      sizeInv: 10,
      totalInv: 0,
      libraryArray: [],
    }
  },

  methods: {
    searchData() {
      this.$http
        .get('/api/book/list', {
          params: this._handerParams()
        })
        .then(res => {
          if (res.code == 0) {
            this.tableData = res.data.records
            this.total = res.data.total
            this.current = res.data.current
            this.size = res.data.size
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log(err.message)
        })
    },
    searchDataInv() {
      this.$http
        .get('/api/bookInventory/list', {
          params: {
            bookId: this.bookId
          }
        })
        .then(res => {
          if (res.code == 0) {
            this.tableDataInv = res.data.records
            this.totalInv = res.data.total
            this.currentInv = res.data.current
            this.sizeInv = res.data.size
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log(err.message)
        })
    },
    /**
     * 加载分类
     */
    loadCatalog() {
      this.$http
        .get('/api/bookCatalog/all-list', {
          params: {}
        })
        .then(res => {
          if (res.code == 0) {
            this.catalogArray = [];
            res.data.forEach(item => {
              this.catalogArray.push({ label: item.catalogName, value: item.id, code: item.catalogCode });
            })
            this.searchCondition[6].options = this.catalogArray;
          }
        })
        .catch(err => {
          console.log(err.message)
        })
    },
    /**
 * 加载分类
 */
    loadLibraryBranch() {
      this.$http
        .get('/api/libraryBranch/all-list', {
          params: {}
        })
        .then(res => {
          if (res.code == 0) {
            this.libraryArray = [];
            res.data.forEach(item => {
              this.libraryArray.push({ label: item.libraryName, value: item.id });
            })
            this.searchConditionInv[0].options = this.libraryArray;
          }
        })
        .catch(err => {
          console.log(err.message)
        })
    },
    /**
     * 查询条件处理        
     */
    _handerParams() {
      const params = {
        current: this.current,
        size: this.size,
        bookName: this.searchForm.bookName,
        bookBarCode: this.searchForm.bookBarCode,
        author: this.searchForm.author,
        publisher: this.searchForm.publisher,
        interpreter: this.searchForm.interpreter,
        printing: this.searchForm.printing,
        catalogName: this.searchForm.catalogName,
        canBorrow: this.searchForm.canBorrow
      }
      return params
    },
    /**
     * 新增修改数据
     */
    addAndEdit() {
      // 设置账号栏位可编辑
      for (const item in this.formField) {
        this.formField[item] = ''
      }
      this.formControl[1].readonly = true;
      this.formControl[9].options = this.catalogArray;
      this.formField.borrowDay = "60";
      this.showForm = true
    },
    addAndEditInv() {
      // 设置账号栏位可编辑
      for (const item in this.formFieldInv) {
        this.formFieldInv[item] = ''
      }
      this.formFieldInv.bookName = this.bookInfo.bookName;
      this.formFieldInv.bookId = this.bookInfo.id;
      this.formControlInv[1].readonly = true;
      this.formControlInv[5].options = this.libraryArray;
      this.showFormInv = true
    },
    /**
     * 选择事件
     */
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 点击行触发，选中或不选中复选框
    handleRowClick(row, column, event) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    handleRowClickInv(row, column, event) {
      this.$refs.multipleTableInv.toggleRowSelection(row)
    },
    /**
     * 动态调用方法
     */
    dynamicMethod(methodname, params) {
      this[methodname](params)
    },
    /**
     * 展示查询条件
     */
    showCondition() {

      this.searchCondition[6].options = this.catalogArray;
      this.showSearch = true
      console.log(this.showSearch)
    },
    showConditionInv() {
      this.searchConditionInv[0].options = this.libraryArray;
      this.showSearchInv = true
      console.log(this.showSearch)
    },
    /**
     * 隐藏查询条件
     */
    hidCondition(val) {
      console.log('hiddiv' + val)
      this.showSearch = val
    },
    hidConditionInv(val) {
      console.log('hiddiv' + val)
      this.showSearchInv = val
    },
    /**
     * 设置查询条件
     */
    setCondition(from) {
      const newData = JSON.parse(JSON.stringify(from))
      this.searchForm = newData
      this.searchData()
    },

    setConditionInv(from) {
      const newData = JSON.parse(JSON.stringify(from))
      this.searchFormInv = newData
      this.searchConditionInv[0].options = this.libraryArray;
      // this.searchData()
    },
    /**
     * 保存表单
     */
    saveForm(from) {
      const newData = JSON.parse(JSON.stringify(from))
      this.formField = newData;
      let catalogId = this.formField.catalogId;
      let catalogCode = "", catalogName = "";
      this.catalogArray.forEach(item => {
        if (item.value == catalogId) {
          catalogCode = item.code;
          catalogName = item.label;
        }
      })
      this.formField.catalogCode = catalogCode;
      this.formField.catalogName = catalogName;
      this.$http.post('/api/book/save', this.formField).then(res => {
        this.searchData()
      }).catch(err => {
        console.log(err.message)
      })
    },
    saveFormInv(from) {
      const newData = JSON.parse(JSON.stringify(from))
      this.formFieldInv = newData;
      this.$http.post('/api/bookInventory/save', this.formFieldInv).then(res => {
        this.searchDataInv()
      }).catch(err => {
        console.log(err.message)
      })
    },
    //查看馆藏信息
    handleInventoryClick(row) {
      this.bookId = row.id;
      this.bookInfo = row;
      this.formFieldInv.bookName = row.bookName;
      this.formFieldInv.bookId = row.id;
      this.showDrawer = true;
      this.searchDataInv();
    },
    /**
     * 删除图书
     */
    handleDelClick(row) {
      // 设置账号栏位不可编辑
      this.$confirm('此操作将永久删除该图书, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const idArray = []
        this.$refs.multipleTable.selection.forEach(element => {
          idArray.push(element.id)
        })
        this.$http.post('/api/book/delete', idArray).then(res => {
          if (res.code == '0') {
            this.$message.success(res.msg)
            this.searchData()
          } else {
            this.$message.error(res.msg)
          }
        }).catch(err => {
          console.log(err.message)
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    handleDelInvClick(row) {
      // 设置账号栏位不可编辑
      this.$confirm('此操作将永久删除该图书馆藏, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const idArray = []
        this.$refs.multipleTableInv.selection.forEach(element => {
          idArray.push(element.id)
        })
        this.$http.post('/api/bookInventory/delete', idArray).then(res => {
          if (res.code == '0') {
            this.$message.success(res.msg)
          } else {
            this.$message.error(res.msg)
          }
          this.searchDataInv()
        }).catch(err => {
          console.log(err.message)
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    /**
     * 修改数据  
     */
    handleEditClick(row) {
      // 设置账号栏位不可编辑
      for (const item in this.formField) {
        this.formField[item] = ''
      }
      this.formControl[1].readonly = true
      this.formControl[9].options = this.catalogArray;
      this.showForm = true
      this.formField.bookName = row.bookName
      this.formField.bookBarCode = row.bookBarCode
      this.formField.author = row.author
      this.formField.publisher = row.publisher
      this.formField.publicationDate = row.publicationDate
      this.formField.printing = row.printing
      this.formField.interpreter = row.interpreter
      this.formField.price = row.price
      this.formField.catalogId = row.catalogId
      this.formField.catalogName = row.catalogName
      this.formField.catalogCode = row.catalogCode
      this.formField.canBorrow = row.canBorrow
      this.formField.borrowDay = row.borrowDay
      this.formField.id = row.id
    },
    /**
     * 修改数据
     */
    handleEditInvClick(row) {
      // 设置账号栏位不可编辑
      for (const item in this.formFieldInv) {
        this.formFieldInv[item] = ''
      }
      this.formControlInv[1].readonly = true
      this.formControlInv[5].options = this.libraryArray;
      this.showFormInv = true
      this.formFieldInv.bookName = row.bookName
      this.formFieldInv.bookId = row.bookId
      this.formFieldInv.author = row.author
      this.formFieldInv.totalQty = row.totalQty
      this.formFieldInv.inPavilion = row.inPavilion
      this.formFieldInv.borrowQty = row.borrowQty
      this.formFieldInv.libraryId = row.libraryId
      this.formFieldInv.id = row.id
    },
    /**
     * 隐藏编辑表单
     */
    hidForm(val) {
      console.log('hiddiv' + val)
      this.showForm = val
    },
    hidFormInv(val) {
      console.log('hiddiv' + val)
      this.showFormInv = val
    },
    /**
     * 删除图书
     */
    delete() {
      if (this.$refs.multipleTable.selection.length <= 0) {
        this.$message.warning('请选择要操作的图书')
        return
      }
      this.$confirm('此操作将永久删除选择的图书, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const idArray = []
        this.$refs.multipleTable.selection.forEach(element => {
          idArray.push(element.id)
        })
        this.$http.post('/api/book/delete', idArray).then(res => {
          if (res.code == '0') {
            this.$message.success(res.msg)
            this.searchData()
          } else {
            this.$message.error(res.msg)
          }
        }).catch(err => {
          console.log(err.message)
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    /**
     * 自定义列修改
     */
    changeColumns(val) {
      console.log('changeColumns--' + val)
      this.tableColumns = []
      this.$nextTick(() => {
        this.tableColumns = val
      })
    },
    changeColumnsInv(val) {
      console.log('changeColumns--' + val)
      this.tableColumnsInv = []
      this.$nextTick(() => {
        this.tableColumnsInv = val
      })
    },
    /**
     * table每页数字变化
     */
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.size = val
      this.searchData()
    },
    handleSizeChangeInv(val) {
      console.log(`每页 ${val} 条`)
      this.sizeInv = val
      this.searchDataInv()
    },
    /**
     * table页数变化
     */
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.current = val
      this.searchData()
    },
    handleCurrentChangeInv(val) {
      console.log(`当前页: ${val}`)
      this.currentInv = val
      this.searchDataInv()
    }
  },
  created() {
    this.tableHeight = document.documentElement.clientHeight - 280
    //
    this.tableColumns = this.defaultColumns
    this.searchData()
    this.loadCatalog();
    this.loadLibraryBranch();
  }
}
</script>
